package com.itmck.exception;

import com.itmck.dto.ApiResultResponse;
import org.apache.shiro.ShiroException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.authz.UnauthorizedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;


/**
 * 统一捕捉shiro的异常，返回给前台一个json信息，前台根据这个信息显示对应的提示，或者做页面的跳转。
 */
@ControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {

    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    //不满足@RequiresGuest注解时抛出的异常信息
    private static final String GUEST_ONLY = "Attempting to perform a guest-only operation";


    @ExceptionHandler(ShiroException.class)
    @ResponseBody
    public ApiResultResponse<String> handleShiroException(ShiroException e) {
        String eName = e.getClass().getSimpleName();
        log.error("shiro执行出错：{}", eName);
        return ApiResultResponse.error("鉴权或授权过程出错", "500");
    }


    /**
     * 处理shiro登录异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(UnauthenticatedException.class)
    @ResponseBody
    public ApiResultResponse<String> UnauthenticatedEx(UnauthenticatedException e) {
        return ApiResultResponse.error("用户未登录", "401");

    }


    @ExceptionHandler(IncorrectCredentialsException.class)
    @ResponseBody
    public ApiResultResponse<String> IncorrectCredentialsEx(IncorrectCredentialsException e) {
        return ApiResultResponse.error("权限异常", "401");
    }


    /**
     * 处理shiro权限
     *
     * @return
     */
    @ExceptionHandler(UnauthorizedException.class)
    @ResponseBody
    public ApiResultResponse<String> page403() {
        return ApiResultResponse.error("用户没有访问权限", "403");
    }

}